﻿Imports System.IO
Imports System.Text
Imports System.Text.Encoding
Imports System.IO.FileStream
Imports SolidWorks.Interop.sldworks
Imports System.Windows.Forms.TreeView
Imports System.Windows.Forms.ListView
Imports Microsoft.VisualBasic.Strings

Module fs

    Public Declare Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" (ByVal hwnd As Int32, ByVal lpOperation As String, ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Int32) As Long

    'Public Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hWnd As Long, ByVal wMsg As Long, ByVal wParam As Long, ByVal lParam As Any) As Long
    Public Declare Function ShellExecuteEx Lib "shell32" (ByVal lpSEI As SHELLEXECUTEINFO) As Long

    Public Const SEE_MASK_INVOKEIDLIST = &HC

    Public Structure SHELLEXECUTEINFO
        Dim cbSize As Long
        Dim fMask As Long
        Dim hWnd As Long
        Dim lpVerb As String
        Dim lpFile As String
        Dim lpParameters As String
        Dim lpDirectory As String
        Dim nShow As Long
        Dim hInstApp As Long
        Dim lpIDList As Long
        Dim lpClass As String
        Dim hkeyClass As Long
        Dim dwHotKey As Long
        Dim hIcon As Long
        Dim hProcess As Long
    End Structure

    ' 判断文件流编码类型  (文件名)
    Public Function GetEncoding(ByVal FileFullName As String) As Encoding

        Dim fs As FileStream = New FileStream(FileFullName, FileMode.Open, FileAccess.Read)
        Dim r As BinaryReader = New BinaryReader(fs, System.Text.Encoding.Default)
        Dim ss() As Byte = r.ReadBytes(3)
        r.Close()

        If (ss(0) >= 239) Then
            Return Encoding.UTF8
            If ((ss(0) = 254) AndAlso (ss(1) = 255)) Then
                Return Encoding.BigEndianUnicode
            ElseIf ((ss(0) = 255) AndAlso (ss(1) = 254)) Then
                Return Encoding.Unicode
            Else
                Return Encoding.Default
            End If
        Else
            Return Encoding.Default
        End If
    End Function

    '读取文件每行到listbox(文件名,ListBox对象)
    Public Sub ReadTextLinesFromFileToListBox(ByVal FileFullName As String, ByVal LB As ListBox)
        Dim File As New StreamReader(FileFullName, Encoding.Default)
        Dim OneLine As String
        LB.Items.Clear()
        OneLine = File.ReadLine()
        While (OneLine <> "")
            LB.Items.Add(OneLine)
            OneLine = File.ReadLine()
        End While
        File.Close()
    End Sub



    '读入自定义属性文件内容
    Public Sub Get_Custom_Properties()
        'Dim CustomProperty_Name As String = Nothing

        'CustomProperty_Name = ""

        'ReadTextLinesFromFileToListBox(Custom_Properties_File, LB)
        'For Each LI In LB.Items
        '    CustomProperty_Name = CustomProperty_Name & "," & LI.ToString
        'Next
        'CustomProperty_Name = Mid(CustomProperty_Name, 2)

        'CustomPropertyNames = Split(CustomProperty_Name, ",")

    End Sub

  
    '判断文件是否为临时文件(文件名)
    Public Function IsTempFile(ByVal FileFullName As String) As Boolean
        If IsFileExsts(FileFullName) = True Then
            If Microsoft.VisualBasic.Strings.Left(GetOnlyname(FileFullName), 2) = "~$" Then
                IsTempFile = True
            Else
                IsTempFile = False
            End If
        Else
            IsTempFile = False
        End If
    End Function

   
    '遍历文件夹(文件夹,方式,listview 或treeview 对象)
    Public Sub TransFiles(ByVal strDirect As String, ByVal Fun As String, ByVal ListObject As Object)
        On Error Resume Next

        Dim Node As TreeNode

        Dim mFileInfo As System.IO.FileInfo
        Dim mDir As System.IO.DirectoryInfo
        Dim mDirInfo As New System.IO.DirectoryInfo(strDirect)

        Dim FileFullName As String
        Dim Nit As NodeIconText

        Dim KeyIndex As Integer
        Dim vDepend As Object
        Dim SubFullName As String
        Dim SubName As String

        Dim swApp As SldWorks

        swApp = CreateObject("SldWorks.Application")

        If Not (strDirect Is Nothing) Then

            Debug.Print("**********************************")

            Debug.Print(strDirect)

            For Each mFileInfo In mDirInfo.GetFiles()

                Debug.Print(mFileInfo.FullName)     '你可以修改代码添加到你的数组中 
                FileFullName = mFileInfo.FullName
                '-------------------------------------------------------
                If IsTempFile(FileFullName) = True Then
                    GoTo 999
                End If

                If DoModel = DRW And Fun <> ASM Then   '扫描到 listview
                    If UCase(mFileInfo.Extension) = DRW Then
                        If InListView(ListObject, FileFullName) = -1 Then

                            If InListView(ListObject, FileFullName) <> -1 Then
                                GoTo 999
                            End If

                            Dim LVI As ListViewItem = ListObject.Items.Add(ListObject.Items.Count + 1)
                            LVI.SubItems.Add(FileFullName)

                            If IsGetNo = 1 Then
                                LVI.SubItems.Add(GetCustomProperty(FileFullName, Part_Number, True))
                            Else
                                LVI.SubItems.Add("")
                            End If

                        End If

                    End If
                ElseIf DoModel = PRT And Fun <> ASM Then '扫描到 treeview

                    '不扫描工程图
                    If IsSWFile(mFileInfo.FullName, DRW) = True And Fun = PRT Then
                        GoTo 999
                    End If

                    '已有文件
                    If IsInTreeView(ListObject, FileFullName) = True Then
                        GoTo 999
                    End If

                    '-------------
                    '文件
                    Nit = GetImageIndex(FileFullName, True)

                    If Nit.IconIndex > 4 Then GoTo 999

                    If IsInTreeView(ListObject, FileFullName) = True Then
                        GoTo 999
                    End If

                    Node = ListObject.Nodes.Add("", GetOnlyname(FileFullName), Nit.IconIndex, Nit.IconIndex)
                    KeyIndex = Node.Index
                    Node.ToolTipText = FileFullName

                    Get_Depend(Node, FileFullName)

                ElseIf Fun = ASM Then '检测未使用零件，扫描到 listbox

                    If UCase(mFileInfo.Extension) = ASM Then
                        ListObject.items.add(FileFullName)

                        '获取全子集
                        vDepend = swApp.GetDocumentDependencies2(FileFullName, True, True, False)
                        '获取工程图到listbox
                        FileFullName = ChangeFileExe(FileFullName, DRW)   '添加工程图到listbox
                        If IsFileExsts(FileFullName) = True Then
                            ListObject.items.add(FileFullName)
                        End If

                        If vDepend Is Nothing = False Then
                            For Index = 0 To (UBound(vDepend) - 1) / 2
                                SubName = vDepend(2 * Index)   '简名
                                SubFullName = vDepend(2 * Index + 1)  '全名
                                ListObject.items.add(SubFullName)   '添加零件到listbox

                                SubFullName = ChangeFileExe(SubFullName, DRW)   '添加工程图到listbox
                                If IsFileExsts(SubFullName) = True Then
                                    ListObject.items.add(SubFullName)
                                End If

                            Next
                        End If
                    End If
                End If

                    '---------------------------------------------------------
999:
            Next

            For Each mDir In mDirInfo.GetDirectories
                TransFiles(mDir.FullName, Fun, ListObject)
            Next

        End If

    End Sub

    '写csv bom表
    Public Sub Write_Csv(ByVal Csv_File As String, ByVal SldDrwFile As SLDDRW_File, ByVal Rows() As String)
        Dim Csv_String As String
        Dim i As Short

        Csv_String = SldDrwFile.Part_Name

        For i = 0 To UBound(Rows)
            If InStr(Rows(i), "#") = 0 Then
                Csv_String = Csv_String & "," & SearchInCsv(SldDrwFile, Rows(i))
            Else
                Csv_String = Csv_String & "," & CalcStr(ReplaceFunction(Rows(i), SldDrwFile))
            End If
        Next i

        WirteLineString(Csv_File, Csv_String)

    End Sub

    '从自定义属性中获取指定名字的值
    Public Function SearchInCsv(ByVal SldDrwFile As SLDDRW_File, ByVal CustomPropertyName As String) As String
        Dim i As Short
        SearchInCsv = ""
        For i = 0 To SldDrwFile.CustomPropertyCount
            If CustomPropertyName = SldDrwFile.CustomProperty(i).Name Then
                SearchInCsv = SldDrwFile.CustomProperty(i).Evaluated
                Exit For
            End If
        Next i

    End Function

    '写一行string 到 文件
    Public Function WirteLineString(ByVal FileFullName As String, ByVal LineString As String) As Boolean
        Try
            If IsFileExsts(FileFullName) = False Then
                System.IO.File.AppendAllText(FileFullName, LineString, System.Text.Encoding.GetEncoding(936))
            Else
                LineString = vbCrLf & LineString
                System.IO.File.AppendAllText(FileFullName, LineString, System.Text.Encoding.GetEncoding(936))
            End If
        Catch ex As IOException
            MsgBox(ex.GetType().Name)
        End Try

    End Function

    '判断一个文件是否在文件列表中,返回index
    Public Function InListView(ByVal LV As ListView, ByVal FileFullName As String) As Integer
        Dim LVI As ListViewItem

        LVI = LV.FindItemWithText(FileFullName)

        If (LVI IsNot Nothing) Then
            Return LVI.Index
        End If

        Return -1

    End Function

    '判断一个文件是否在树中
    Public Function IsInTreeView(ByVal TL As TreeView, ByVal FileFullName As String) As Boolean
        Dim Node As TreeNode
        For Each Node In TL.Nodes
            If Node.ToolTipText = FileFullName Then
                IsInTreeView = True
                Exit Function
            End If
        Next
        IsInTreeView = False

    End Function

    '重建文件列表序号
    Public Sub ReBuiltNumber(ByVal LV As ListView)
        Dim LVI As ListViewItem
        Dim i As Short
        i = 1
        For Each LVI In LV.Items
            LVI.Text = i
            i = i + 1
        Next

    End Sub



    '对比删除文件
    Public Sub ReMoveUnusedFile(ByVal strDirect As String, ByVal ListObject As Object)
        On Error Resume Next
        Dim mFileInfo As System.IO.FileInfo
        Dim mDir As System.IO.DirectoryInfo
        Dim mDirInfo As New System.IO.DirectoryInfo(strDirect)

        If Not (strDirect Is Nothing) Then
            Debug.Print("**********************************")
            Debug.Print(strDirect)

            For Each mFileInfo In mDirInfo.GetFiles()
                If InStr(".SLDASM.SLDPRT.SLDDRW", UCase(mFileInfo.Extension)) <> 0 Then
                    Debug.Print(mFileInfo.FullName)     '你可以修改代码添加到你的数组中 

                    If ListObject.FindString(mFileInfo.FullName) = ListBox.NoMatches Then
                        'DelFile(mFileInfo.FullName, FileIO.RecycleOption.SendToRecycleBin)
                        ReMoveFileToFolder(mFileInfo.FullName, strDirect & "\unusedfiles")
                    End If

                End If
            Next

            

            For Each mDir In mDirInfo.GetDirectories
                If InStr("unusedfiles", mDir.FullName) <> 0 Then
                    ReMoveUnusedFile(mDir.FullName, ListObject)
                End If
            Next
        End If

    End Sub
End Module
